package top.easyblog.core.support.filter;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: frank.huang
 * @date: 2023-12-22 22:40
 */
@Slf4j
@Component
public class TransformFilterChainFactory {

    @Autowired
    private List<TransformFilter> transformFilterList;


    public TransformFilterChain buildTransformFilterChain(TransformContext transformContext) {
        List<TransformFilterInstance> filterInstances = transformFilterList.stream()
                .map(filter -> new TransformFilterInstance(filter, filter.order(), filter.getClass().getSimpleName()))
                .sorted(Comparator.comparingInt(TransformFilterInstance::getOrder))
                .collect(Collectors.toList());

        DefaultTransformFilterChain defaultTransformFilterChain = new DefaultTransformFilterChain();
        filterInstances.forEach(transformFilterInstance -> {
            TransformFilter filter = transformFilterInstance.getFilter();
            BaseNamingTransformFilter baseNamingTransformFilter = new BaseNamingTransformFilter(filter) {
                @Override
                public String filterName() {
                    return transformFilterInstance.getFilterName();
                }
            };
            defaultTransformFilterChain.addTransformFilter(baseNamingTransformFilter);
            baseNamingTransformFilter.init(transformContext);
        });
        return defaultTransformFilterChain;
    }


    @Getter
    @RequiredArgsConstructor
    private static class TransformFilterInstance {
        private final TransformFilter filter;
        private final int order;
        private final String filterName;
    }
}
